﻿package de.gameduell.framework.facebook.app.pyramide {
	import de.gameduell.framework.facebook.app.Controller;
	import de.gameduell.framework.facebook.app.GameData;
	import de.gameduell.framework.facebook.app.PageManager;
	import de.gameduell.framework.facebook.app.popups.CoinsCollectedPopup;
	import de.gameduell.framework.facebook.app.popups.LevelUpPopup;
	import de.gameduell.framework.facebook.app.popups.SelectBrickPoup;
	import de.gameduell.framework.facebook.app.popups.ShareLevelUpPopup;
	import de.gameduell.framework.facebook.app.popups.TempleGamePopup;

	import fl.transitions.easing.None;
	import fl.transitions.easing.Regular;

	import de.gameduell.framework.debug.Debug;
	import de.gameduell.framework.facebook.FBBaseAppLayout;
	import de.gameduell.framework.facebook.FBBaseController;
	import de.gameduell.framework.gui.animation.GDTween;
	import de.gameduell.framework.gui.button.Button;
	import de.gameduell.framework.gui.button.ButtonEvent;
	import de.gameduell.framework.gui.util.Formatter;
	import de.gameduell.framework.gui.util.ToolTip;
	import de.gameduell.framework.gui.wrapper.SpriteWrapper;
	import de.gameduell.framework.locale.LocaleData;
	import de.gameduell.framework.queue.GDAction;
	import de.gameduell.framework.queue.GDActionQueue;
	import de.gameduell.framework.queue.PopupAction;
	import de.gameduell.framework.util.Library;

	import flash.display.Bitmap;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.text.TextField;

	public class BrickView extends SpriteWrapper {
		public static const BRICKVIEW_CHANGED:String = "BRICKVIEW_CHANGED";
		protected var brick:Brick;
		protected var library:Library;
		protected var controller:Controller;
		protected var layout:FBBaseAppLayout;
		protected var coinsText:TextField;
		protected var pageManager:PageManager;
		protected var brickGraphics:Sprite;
		protected var playButton:Button;
		protected var progressBar:Sprite;
		protected var progressClip:Sprite;
		protected var onTopClip:MovieClip;
		protected var brickOverlay:Sprite;
		protected var replayButton:Button;
		protected var brickOverLayTween:GDTween;
		protected var scoreText:TextField;
		protected var localeData:LocaleData;
		protected var stateLayer:Sprite;
		protected var switchBrickButton:Button;
		protected var isBlocked:Boolean;
		protected var brickClip:MovieClip;
		protected var borderStateClip:MovieClip;

		public function BrickView(aBrick:Brick, aStateLayer:Sprite, aIsBlocked:Boolean = true) {
			super(new Sprite());
			isBlocked = aIsBlocked;
			brick = aBrick;
			stateLayer = aStateLayer;
			localeData = LocaleData.getInstance();
			library = Library.getInstance();
			pageManager = PageManager.getInstance();
			controller = Controller.getInstance();
			layout = FBBaseAppLayout.getInstance();
			
			brickClip = library.createClip("brick");
			sprite.addChild(brickClip);
			
			brickOverlay = library.createSprite("brickOverlay");
			brickOverlay.alpha = 0;
			brickOverlay.visible = false;
			stateLayer.addChild(brickOverlay);

			replayButton = new Button(brickOverlay.getChildByName("replayButton") as Sprite, "replayButton");
			replayButton.addEventListener(ButtonEvent.CLICK, onReplayMission);
			replayButton.toolTip = true;

			switchBrickButton = new Button(brickOverlay.getChildByName("switchBrickButton") as Sprite, "switchBrickButton");
			switchBrickButton.addEventListener(ButtonEvent.CLICK, onReSkinBrick);
			switchBrickButton.toolTip = true;
			
			scoreText = brickOverlay.getChildByName("brickScoreText") as TextField;
			
			onTopClip = brickClip.getChildByName("topBrickClip") as MovieClip;
			onTopClip.visible = false;
			
			coinsText = brickClip.getChildByName("coinsText") as TextField;
			brickGraphics = brickClip.getChildByName("brickGraphics") as Sprite;

			controller.gameData.addEventListener(GameData.APP_COINS_CHANGED, onUpdate); // TODO - can be done via model?
			progressClip = brickClip.getChildByName("progress") as Sprite;
			new ToolTip("tooltip", "brick_progress_tooltip", progressClip, true);
			
			coinsText = progressClip.getChildByName("coinsText") as TextField;
			progressBar = progressClip.getChildByName("progressBar") as Sprite;
			progressBar.x = -progressBar.width;
			
			playButton = new Button(brickClip.getChildByName("playButton") as Sprite, "brickPlayButton");
			playButton.addEventListener(ButtonEvent.CLICK, startGame);
			playButton.active = false;
			
			onUpdate();
			onStateChanged();
			unUpdateScore();

			if(isBlocked) {
				progressClip.visible = false;
				playButton.sprite.visible = false;
				playButton.active = false;
				replayButton.sprite.visible = false;
				replayButton.active = false;
				brickOverlay.visible = false;
				controller.removeEventListener(FBBaseController.GAME_END, showCoinsCollectedPopup);
				brickOverlay.removeEventListener(MouseEvent.MOUSE_OVER, fadeInOverlay);
				brickOverlay.removeEventListener(MouseEvent.MOUSE_OUT, fadeOutOverlay);
				controller.gameData.removeEventListener(GameData.APP_COINS_CHANGED, onUpdate);
			} else {
				brick.addEventListener(Brick.BRICK_STATE_CHANGED, onStateChanged);
				brick.addEventListener(Brick.BRICK_CHANGED, onUpdate);
				brick.addEventListener(Brick.BRICK_SCORE_CHANGED, unUpdateScore);
				brick.addEventListener(Brick.BRICK_TYPE_CHANGED, onTypeChanged);
			}
		}

		public function set align(aPos:String):void {
			borderStateClip.gotoAndStop(aPos);
		}

		protected function onReSkinBrick(event:ButtonEvent):void {
			var selectBrickPopup:SelectBrickPoup = new SelectBrickPoup(brick);
			selectBrickPopup.show();
		}

		override public function set position(aPoint:Point):void {
			super.position = aPoint;
			brickOverlay.x = aPoint.x;
			brickOverlay.y = aPoint.y;
		}

		protected function unUpdateScore(event:Event = null):void {
			scoreText.text = Formatter.formatNumberEnglish(String(brick.score), ",");
		}

		protected function fadeInOverlay(event:Event = null):void {
			if(brickOverLayTween != null) {
				brickOverLayTween.stop();
			}
			brickOverLayTween = new GDTween(brickOverlay, "alpha", None.easeNone, brickOverlay.alpha, 1, 0.2, true);
			brickOverLayTween.start();
		}

		protected function fadeOutOverlay(event:Event = null):void {
			if(brickOverLayTween != null) {
				brickOverLayTween.stop();
			}
			brickOverLayTween = new GDTween(brickOverlay, "alpha", None.easeNone, brickOverlay.alpha, 0, 0.2, true);
			brickOverLayTween.start();
		}

		protected function showCoinsCollectedPopup(event:Event):void {
			Debug.trace("BrickView::showCoinsCollectedPopup: " + brick.id + ":" + controller.lastGameResult.score, Debug.WARNING);
			if(controller.activeTaskId == brick.id) {
				brick.score = controller.lastGameResult.score > brick.score ? controller.lastGameResult.score : brick.score;
			}
			var progressBarGlobalPos:Point = localToGlobal(new Point(progressClip.x, progressClip.y));
			new PopupAction(new CoinsCollectedPopup(progressBarGlobalPos), true, "showCoinsCollectedPopup");
			controller.checkLives(); // TODO - timing ... show as last popup
		}

		protected function onReplayMission(event:Event):void {
			Debug.trace("BrickView::onReplayMission: brickId: " + brick.id);
			new GDAction(pageManager.prepareGameStart, [], true);
			new GDAction(controller.startGameWithId, [brick.id, layout.contentPosition.x, layout.contentPosition.y, true], true);
		}

		protected function startGame(event:Event):void {
			Debug.trace("BrickView::startGame: brickId: " + brick.id + " " + GDActionQueue.getInstance().getQueuedActionDescriptions());
			new GDAction(pageManager.prepareGameStart, [], true);
			new GDAction(controller.startGameWithId, [brick.id, layout.contentPosition.x, layout.contentPosition.y], true);
		}

		protected function onTypeChanged(event:Event):void {
			try {
				brickGraphics.removeChildAt(0);
				borderStateClip = pageManager.getPicFromLib(brick.brickType);
				brickGraphics.addChild(borderStateClip);
				borderStateClip.cacheAsBitmap = true;
				dispatchEvent(new Event(BRICKVIEW_CHANGED));
			}catch(e:Error) {
				Debug.trace("BrickView::onTypeChanged: nothing to remove ...", Debug.WARNING);
			}
		}

		protected function onStateChanged(event:Event = null):void {
			brickOverlay.removeEventListener(MouseEvent.MOUSE_OVER, fadeInOverlay);
			brickOverlay.removeEventListener(MouseEvent.MOUSE_OUT, fadeOutOverlay);
			
			switch(brick.state) {
				case Brick.STATE_UNDEFINED:
					sprite.visible = false;
					playButton.active = false;
					break;
				case Brick.STATE_CONSTRUCTION:
					sprite.alpha = 0;
					sprite.visible = true;
					brickGraphics.addChild(library.createSprite("brick_const_1"));
					playButton.active = true;
					var fadeTween:GDTween = new GDTween(sprite, "alpha", Regular.easeIn, 0, 1, 0.5, true);
					fadeTween.start();
					controller.addEventListener(FBBaseController.JACKPOT_GAME_END, showCoinsCollectedPopup);
					controller.addEventListener(FBBaseController.GAME_END, showCoinsCollectedPopup);
					replayButton.sprite.visible = false;
					switchBrickButton.sprite.visible = false;
					brickOverlay.visible = true;
					brickOverlay.addEventListener(MouseEvent.MOUSE_OVER, fadeInOverlay);
					brickOverlay.addEventListener(MouseEvent.MOUSE_OUT, fadeOutOverlay);

					break;
				case Brick.STATE_SELECT:
					controller.removeEventListener(FBBaseController.JACKPOT_GAME_END, showCoinsCollectedPopup);
					controller.removeEventListener(FBBaseController.GAME_END, showCoinsCollectedPopup);
					sprite.visible = true;
					playButton.active = true;
					progressClip.visible = true;
					try {
						brickGraphics.removeChildAt(0);
					}catch(e:Error) {
					}
					brickGraphics.addChild(new Bitmap(library.createBitmapData("brick_select_1.png", 90, 60)));
					brickCompleted();
					break;
				case Brick.STATE_COMPLETED:
					brickOverlay.addEventListener(MouseEvent.MOUSE_OVER, fadeInOverlay);
					brickOverlay.addEventListener(MouseEvent.MOUSE_OUT, fadeOutOverlay);
					controller.removeEventListener(FBBaseController.JACKPOT_GAME_END, showCoinsCollectedPopup);
					controller.removeEventListener(FBBaseController.GAME_END, showCoinsCollectedPopup);
					sprite.visible = true;
					playButton.active = false;
					playButton.sprite.visible = false;
					progressClip.visible = false;
					try {
						brickGraphics.removeChildAt(0);
					}catch(e:Error) {
						// 
					}
					borderStateClip = pageManager.getPicFromLib(brick.brickType); //library.createClip(brick.brickType);
					brickGraphics.addChild(borderStateClip);
					controller.gameData.removeEventListener(GameData.APP_COINS_CHANGED, onUpdate);
					replayButton.sprite.visible = true;
					switchBrickButton.sprite.visible = true;
					brickOverlay.visible = true;
					break;
			}
		}

		protected function brickCompleted():void {
			new PopupAction(new LevelUpPopup(brick), true);
			new PopupAction(new ShareLevelUpPopup(brick), true);
			// featureCheck: is castleGame enabled?
			// new PopupAction(new TempleGamePopup(), true);
			new GDAction(controller.gameData.pyramid.nextBrick, [], true, "nextBrick");
		}

		//		public function setIsOnTop(isTop:Boolean, aRowIndex:int = -1):void {
		//			Debug.trace("BrickView::setIsOnTop: " + isTop + ":" + aRowIndex + ":" + brick.id, Debug.DEFAULT);
		//			if(brick.state != Brick.STATE_CONSTRUCTION) {
		//				onTopClip.alpha = isTop ? 1 : 0;
		//				
		//				if(!onTopClip.visible && isTop) {
		//					onTopClip.visible = isTop;
		//					if(aRowIndex != -1) {
		//						onTopClip.gotoAndStop(aRowIndex);
		//					}
		////					blink();
		//				}
		//				brickGraphics.visible = !isTop;
		//				//				if(isTop && aRowIndex != -1) {
		//				//					addStairs(aRowIndex);
		//				//				}
		//				switchBrickButton.active = false;
		//			} else {
		//				brickGraphics.visible = true;
		//				switchBrickButton.active = true;
		//			}
		//		}

		//		protected function addStairs(aHeight:int):void {
		//			var stairs:SpriteWrapper = new Stairs(aHeight);
		//			stairs.y = 59;
		//			stairs.x = -45;
		//			stairs.mouseEnabled = false;
		//			stairs.mouseChildren = false;
		//			
		//			onTopClip.addChild(stairs.sprite);
		//		}
		protected function onUpdate(event:Event = null):void {
			var percent:Number = (controller.gameData.coins * 100) / brick.coinsNeeded;
			if(percent < 100) {
				var position:Number = (90 * percent) / 100 - 90;
				progressBar.x = position;
				coinsText.text = controller.gameData.coins + "/" + brick.coinsNeeded;
				if(brick.state == Brick.STATE_CONSTRUCTION) {
					localeData.setValue("coinsNeededDiff", String(brick.coinsNeeded - controller.gameData.coins));
				}
			} else {
				progressBar.x = 0;
				coinsText.text = brick.coinsNeeded + "/" + brick.coinsNeeded;
				if(brick.state == Brick.STATE_CONSTRUCTION) {
					localeData.setValue("coinsNeededDiff", String(brick.coinsNeeded - controller.gameData.coins));
				}
			}
		}

		//		protected function blink():void {
		//			var flashTimer:Timer = new Timer(500, 3);
		//			flashTimer.addEventListener(TimerEvent.TIMER, flash);
		//			flashTimer.start();
		//		}

		//		protected function flash(event:Event):void {
		//			onTopClip.transform.colorTransform = new ColorTransform(2, 2, 2);
		//			var flashTimer:Timer = new Timer(300, 1);
		//			flashTimer.addEventListener(TimerEvent.TIMER, restoreColors);
		//			flashTimer.start();
		//		}

		//		protected function restoreColors(event:Event):void {
		//			onTopClip.transform.colorTransform = new ColorTransform();
		//		}
		public function destroy():void {
			replayButton.removeEventListener(ButtonEvent.CLICK, onReplayMission);
			switchBrickButton.removeEventListener(ButtonEvent.CLICK, onReSkinBrick);
			controller.gameData.removeEventListener(GameData.APP_COINS_CHANGED, onUpdate);
			playButton.removeEventListener(ButtonEvent.CLICK, startGame);
			if(brick != null) {
				brick.removeEventListener(Brick.BRICK_STATE_CHANGED, onStateChanged);
				brick.removeEventListener(Brick.BRICK_CHANGED, onUpdate);
				brick.removeEventListener(Brick.BRICK_SCORE_CHANGED, unUpdateScore);
				brick.removeEventListener(Brick.BRICK_TYPE_CHANGED, onTypeChanged);
			}
			controller.removeEventListener(FBBaseController.JACKPOT_GAME_END, showCoinsCollectedPopup);
			controller.removeEventListener(FBBaseController.GAME_END, showCoinsCollectedPopup);
			brickOverlay.removeEventListener(MouseEvent.MOUSE_OVER, fadeInOverlay);
			brickOverlay.removeEventListener(MouseEvent.MOUSE_OUT, fadeOutOverlay);

			stateLayer.removeChild(brickOverlay);			
			brickClip.removeChild(onTopClip);
			brickClip.removeChild(brickGraphics);						
			brickClip.removeChild(progressClip);
			
			brickClip.visible = false;
				
			sprite.removeChild(brickClip);
			brickClip = null;
		}
	}
}